package org.yanfengying.car.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.yanfengying.car.controller.CarDetailController;
import org.yanfengying.car.domain.Car;
import org.yanfengying.car.domain.CarDetail;
import org.yanfengying.car.domain.CarOnlineAuditLog;
import org.yanfengying.car.domain.CarType;
import org.yanfengying.car.mapper.CarDetailMapper;
import org.yanfengying.car.mapper.CarMapper;
import org.yanfengying.car.mapper.CarOnlineAuditLogMapper;
import org.yanfengying.car.mapper.CarResourcesMapper;
import org.yanfengying.car.service.ICarService;
import org.yanfengying.es.doc.CarDoc;
import org.yanfengying.es.repository.CarDocRepository;
import org.yanfengying.org.domain.Employee;
import org.yanfengying.org.domain.Shop;
import org.yanfengying.org.service.IBaiduAiService;
import org.yanfengying.utils.AjaxResult;
import org.yanfengying.utils.LoginContext;
import org.yanfengying.utils.VelocityUtils;
import org.yanfengying.utils.service.impl.BastServerImpl;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yanfengying
 * @since 2022-11-01
 */
@Service
public class CarServiceImpl extends BastServerImpl<Car> implements ICarService {

    @Autowired
    private CarDetailMapper carDetailMapper;
    @Autowired
    private CarResourcesMapper carResourcesMapper;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CarDocRepository carDocRepository;
    @Autowired
    private CarOnlineAuditLogMapper carOnlineAuditLogMapper;
    
    @Autowired
    private IBaiduAiService baiduAiService;
    @Value("${velocity.templatePath}")
    private String templatePath;
    @Value("${velocity.tagetPath}")
    private String tagetPath;
    @Override
    @Transactional
    public void insert(Car car) {
        CarDetail carDetail = car.getCarDetail();
        //调用百度ai进行自动审核
        String text = car.getTitle() + "" + carDetail.getInfo();
        AjaxResult result = baiduAiService.audit(text, car.getCover(), null);

        //封装日志信息
        CarOnlineAuditLog auditLog = new CarOnlineAuditLog();
        auditLog.setAuditTime(new Date());
        if(result.getSuccess()){//审核通过
            auditLog.setState(1);
            auditLog.setNote("自动审核通过");

        }else{
            auditLog.setState(2);
            auditLog.setNote("自动审核失败!原因:"+result.getMessage());
        }

        //状态,时间相关信息
        car.setCreatetime(new Date());
        car.setSeller(LoginContext.getLoginAdmin());
        // 设置状态 0-下架 1-上架
        car.setState(0L);
        // 设置审核状态 0-待审核 1-审核通过 2-审核驳回
        car.setAuditstate(auditLog.getState());
        car.setShopId(LoginContext.getLoginAdmin().getShopId());
        super.insert(car);

        //保存carDetail信息
//        CarDetail carDetail = new CarDetail();
        carDetail.setCarId(car.getId());
        carDetail.setCartitle(car.getTitle());
        auditLog.setCarId(car.getId());
        carOnlineAuditLogMapper.insert(auditLog);
        carDetailMapper.insert(carDetail);

    }

    @Override
    @Transactional
    public void delete(Serializable id) {
        //删除t_car_car内容
        carMapper.delete(id);
        //删除t_car_car_detail相关内容
        carDetailMapper.deleteByCarid(id);
        //删除t_car_car_resource相关内容
        carResourcesMapper.deleteByCarid(id);
        super.delete(id);
    }

    /**
     * 上架操作
     * @param ids
     */
    @Override
    @Transactional
    public void onsale(List<Long> ids) {
        //参数校验
        if(ids == null || ids.size() == 0){//没有值
            throw new RuntimeException("请选中数据后操作");
        }
        //从数据库中查询ids中已通过审核的个数
        Integer count = carMapper.getAuditstateCount(ids);
        if(count < ids.size()){//说明里面包含有审核未通过的
            throw new RuntimeException("请检查选中的数据是否已经全部审核通过");
        }

        //将数据添加到es中
        List<CarDoc> docs = new ArrayList<>();
        List<Car> cars = carMapper.getCarDetailByIds(ids);
        for (Car car:cars){
            CarDoc doc = new CarDoc();
            //快速复制对象
            BeanUtils.copyProperties(car, doc);
            Shop shop = car.getShop();
            if(Objects.nonNull(shop)){
                doc.setShopId(shop.getId());
                doc.setShopName(shop.getName());
                doc.setShopAddress(shop.getAddress());
            }
            //设置类型信息
            CarType cartype = car.getCartype();
            if(Objects.nonNull(cartype)){
                doc.setTypeId(cartype.getId());
                doc.setTypeName(cartype.getName());
            }
            //设置对象的对应详情
            CarDetail carDetail = car.getCarDetail();
            if(Objects.nonNull(carDetail)){
                doc.setCarInfo(carDetail.getInfo());
            }
            docs.add(doc);
        }
        //将数据添加到es中
        carDocRepository.saveAll(docs);

        //修改数据库状态
        carMapper.onsale(ids);

        //填写日志
        Employee loginAdmin = LoginContext.getLoginAdmin();
        List<CarOnlineAuditLog> logs = new ArrayList<>();
        for (Long id : ids) {
            CarOnlineAuditLog log = new CarOnlineAuditLog();
            log.setCarId(id);
            log.setNote(loginAdmin.getUsername()+"对id为"+id+"进行了上架操作");
            log.setState(1);
            log.setAuditTime(new Date());
            log.setAuditId(loginAdmin.getId());
            logs.add(log);
        }
        carOnlineAuditLogMapper.insertBatch(logs);
        //生成上架车辆的静态页面
        staticPage(ids);
    }
    public void staticPage(List<Long> ids){
        //模板的物理路径->根据类加载器获取路径
//        String templatePath = this.getClass().getClassLoader().getResource("").toString()+"/templates/carDetail.vm";
        for(Long id:ids){
            //每次循环都需要调用方法生成静态页面

            //封装数据对象
            System.out.println(this.tagetPath);
            System.out.println(this.templatePath);

            //查询信息
            Car car = carMapper.loadById(id);
            //生成后的文件要存放的物理地址路径->前端的项目下面
            String tagetPath = this.tagetPath + id +".html";
            VelocityUtils.staticByTemplate(car, this.templatePath,tagetPath);
        }
    }

    /**
     * 下架操作
     * @param ids
     */
    @Override
    @Transactional
    public void offsale(List<Long> ids) {
        //参数校验
        if(ids == null || ids.size() == 0){//没有值
            throw new RuntimeException("请选中数据后操作");
        }
        //从es中删除数据
        List<CarDoc> docs = new ArrayList<>();
        for (Long id:ids){
            CarDoc doc = new CarDoc();
            doc.setId(id);
            docs.add(doc);
        }
        carDocRepository.deleteAll(docs);
        carMapper.offsale(ids);//修改数据库状态

        //填写日志  0下架 1上架
        Employee loginAdmin = LoginContext.getLoginAdmin();
        List<CarOnlineAuditLog> logs = new ArrayList<>();
        for (Long id : ids) {
            CarOnlineAuditLog log = new CarOnlineAuditLog();
            log.setCarId(id);
            log.setNote(loginAdmin.getUsername()+"对id为"+id+"进行了下架操作");
            log.setState(0);
            log.setAuditTime(new Date());
            log.setAuditId(loginAdmin.getId());
            logs.add(log);
        }
        carOnlineAuditLogMapper.insertBatch(logs);

    }
}
